package openai

import (
	"chatgpt/helper/code"
	"context"
	gogpt "github.com/sashabaranov/go-openai"
	"github.com/slclub/glog"
	"strings"
)

func (self *AppGPT) ChatCompletion(question *Request) *ChatResponse {
	ctx := context.Background()
	response := &ChatResponse{
		MsgCode: code.SUCCESS,
	}
	if question.Text == "" {
		response.MsgCode = code.DATA_NIL
		glog.Errorf("CHATGPT.ChatCompletion.REQ.TEXT is empty!")
		return response
	}

	cnf := self.Config()
	prompt := question.Text
	if len(cnf.Chat.BotDesc) > 0 {
		prompt = cnf.Chat.BotDesc + " " + question.Text
	}
	if question.User == nil {
		question.User = &User{Role: "user", Name: "TD", UID: "TD-1"}
	}
	glog.Infof("CHATGPT.ChatCompletion.REQ prompt is %s", prompt)
	req := gogpt.ChatCompletionRequest{
		Model:            cnf.Chat.Model,
		MaxTokens:        cnf.Chat.MaxTokens,
		TopP:             cnf.Chat.TopP,
		FrequencyPenalty: cnf.Chat.FrequencyPenalty,
		PresencePenalty:  cnf.Chat.PresencePenalty,
		N:                1,
		Messages: []gogpt.ChatCompletionMessage{
			{Role: question.User.Role, Content: prompt, Name: question.User.Name},
		},
		User: question.User.UID,
		Stop: question.Stop,
	}

	resp, err := self.Client().CreateChatCompletion(ctx, req)
	response.resp = resp
	if err != nil {
		glog.Errorf("CHATGP.ChatCompletionT.RESPONSE.ERROR %v", err)
		response.MsgCode = code.DATA_CALL_ERROR
		return response
	}
	glog.Debugf("CHATGPT.ChatCompletion.RESPONSE.OK")
	return response
}

func (self *AppGPT) ConvChat(question string, model string, user *User, stop string) *Response {
	result := AppChatGPT.ChatCompletion(&Request{Text: question, User: user, Model: model, Stop: strings.Split(stop, ",")})
	res := &Response{
		MsgCode: result.MsgCode,
		Text:    "",
		Tokens:  0,
	}
	if res.MsgCode != code.SUCCESS {
		return res
	}
	if len(result.resp.Choices) == 0 {
		return res
	}
	data := result.resp.Choices[0].Message
	res.Text = data.Content
	res.Tokens = result.resp.Usage.TotalTokens
	//usage := res.resp.Usage // 使用tokens 情况

	return res
}
